<script setup lang="ts">
import { computed } from 'vue';
import Taro, { useRouter } from '@tarojs/taro';

import ApiOrder from '@/api/order';
import useFetch from '@/hooks/useFetch';
import ApiPayment from '@/api/payment';
import ApiActivity from '@/api/activity';

import Page from '@/components/common/Page.vue';
import StepItem from './components/StepItem.vue';
import Result from '@/pages/merchant/components/Result.vue';
import ContentTip from '@/pages/index/components/ContentTip.vue';

import { TActivityApply } from '@/global';


const { params } = useRouter<{
    // 申请报名Idf
    id: `${number}`;
}>();

// 查询报名数据

// 测试用
// const data = ref({
//     audit_status: 1,
//     deposit_status: 0,
// });
const { data, refresh } = useFetch<TActivityApply>(ApiActivity.getApplyActivityDetail, {
    defaultParams: { id: +params.id },
    afterFetch: (res: any) => res.detail,
    showLoading: true
});

/**
 *  支付押金流程
 *  1. 创建订单
 *  2. 获取JSAPI支付参数
 *  3. 发起支付
 *  4. 反馈结果
 */
const createOrderAndPay = async () => {

    const { id, act_id, merchant_id } = data.value;
    const { data: { value } } = await useFetch<{ sn: string; }>(ApiOrder.createDepositOrder, {
        defaultParams: {
            act_id,
            merchant_id,
            act_apply_id: id,
        },
    });

    const {
        data: { value: payParams },
    } = await useFetch<any>(ApiPayment.payment, {
        defaultParams: {
            order_sn: value.sn,
            pay_type: "wechat_pay",
            // 订单类型 1 押金订单 2 普通订单
            service_type: 1,
        },
    });

    Taro.requestPayment({
        timeStamp: payParams.time_stamp,
        nonceStr: payParams.nonce_str,
        package: payParams.package,
        signType: payParams.sign_type,
        paySign: payParams.pay_sign,
    }).then(
        () => {
            Taro.showToast({ title: "支付成功" });

            // 先强制改下状态
            data.value.deposit_status = 1;

            setTimeout(() => {
                refresh();
            }, 2000);
        },
        (err) => {
            console.error("支付失败", err);
            Taro.showToast({ icon: "error", title: "支付失败" });
        }
    );
};

const statusMap = {
    applied: {
        title: "提交成功！",
        desc: "平台将在7个工作日内审核完成，\n请耐心等待审核结果",
        image: "/static/svg/enroll-applyed.svg"
    },
    fail: {
        title: "很遗憾，审核不通过",
        desc: "很抱歉，您未通过本次报名审核，\n详情请咨询客服：CDJNH2020",
        image: "/static/svg/enroll-refused.svg"
    },
    // unpay: {
    //     // title: "提交成功！",
    //     desc: "活动结束后，\n押金将在15个工作日内返还",
    //     btnText: "支付押金"
    // },
};

// 简化状态
const aliasStatus = computed(() => {
    const { audit_status, deposit_status } = data.value || {};
    return audit_status == 2 ? 'fail' : audit_status == 0 ? 'applied' :
        deposit_status == 0 ? 'unpay' : 'success';
});

const resultView = computed(() => {
    const status = aliasStatus.value;
    const res = { ...statusMap[status] };

    // if (status == 'fail') {
    //     res.desc = `原因：${data.value.audit_reason}\n${res.desc}`;
    // }

    return res;
});

// 显示押金金额
const depositAmount = computed(() => (data.value?.deposit_amount ?? 0) / 100);

// 按钮事件
const handleBtnTap = () => {
    switch (aliasStatus.value) {
        case "unpay": createOrderAndPay(); break;
        case "success": Taro.reLaunch({ url: '/pages/merchant/index' }); break;
    }
};
</script>

<template>
    <Page height="260rpx">

        <view class="mt-3 flex justify-around">
            <StepItem type="success" title="提交报名" />
            <StepItem :type="data?.audit_status == 0 ? 'waiting' : data?.audit_status == 2 ? 'fail' : 'success'"
                      :title="data?.audit_status == 0 ? '等待审核' : data?.audit_status == 2 ? '不通过' : '审核通过'" />
            <StepItem title="支付押金"
                      :type="data?.audit_status == 1 ? data?.deposit_status == 0 ? 'waiting' : 'success' : undefined" />
        </view>

        <template v-if="data?.audit_status == 1">

            <ContentTip :congrat="aliasStatus == 'success'"
                        :btn-text="aliasStatus == 'success' ? '返回商家' :
                            aliasStatus == 'unpay' ? '支付押金' : undefined"
                        @btn-tap="handleBtnTap">
                <view class="text-primary text-center">
                    <template v-if="aliasStatus == 'unpay'">
                        <view class="text-lg">审核通过！</view>
                        <view class="text-[54px]">待支付押金</view>
                        <view class="text-[54px]">¥{{ depositAmount }}</view>
                    </template>

                    <view v-else class="mb-5 text-[40px]">
                        <view>恭喜您</view>
                        <view>报名成功！</view>
                    </view>
                </view>

                <template #footer v-if="aliasStatus == 'unpay'">
                    <view class="mt-1 text-lg text-[#9F6C3E] whitespace-pre-line">
                        <view>请于10日内尽快支付押金哦，</view>
                        <view>逾期展位将不做保留。</view>
                    </view>
                </template>
            </ContentTip>
        </template>

        <view v-else class="mt-[200px]">
            <Result v-bind="resultView" />
        </view>
    </Page>
</template>